import Vue from 'vue'
import App from './App.vue'
import router from './router'
import VueRouter from 'vue-router'
import { tokenUrl } from './valid/tokenUrl'
import 'lib-flexible/flexible'

import { Button, Icon, Search, Sidebar, SidebarItem, Tabbar, TabbarItem, Tab, Tabs, Swipe, SwipeItem, NavBar, Checkbox, CheckboxGroup, Collapse, CollapseItem, Tag, Rate, GoodsAction, GoodsActionIcon, GoodsActionButton, Loading, Toast, Form, Field, RadioGroup, Radio, SubmitBar, Empty, Popup, Pagination, Uploader, Cell } from 'vant';

//注册组件
Vue.use(Collapse)
  .use(CollapseItem)
  .use(Rate)
  .use(Loading)
  .use(Checkbox)
  .use(CheckboxGroup)
  .use(Form)
  .use(Field)
  .use(Popup)
  .use(GoodsAction)
  .use(GoodsActionButton)
  .use(GoodsActionIcon)
  .use(Swipe)
  .use(SwipeItem)
  .use(Tab)
  .use(Tabs)
  .use(Button)
  .use(Icon)
  .use(Search)
  .use(Sidebar)
  .use(SidebarItem)
  .use(Tabbar)
  .use(TabbarItem)
  .use(VueRouter)
  .use(NavBar)
  .use(Tag)
  .use(Toast)
  .use(Radio)
  .use(RadioGroup)
  .use(SubmitBar)
  .use(Empty)
  .use(Pagination)
  .use(Uploader)
  .use(Cell)
//注册axios, 这样就可以在组件里面使用
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)




//添加一个axios请求之前拦截器
axios.interceptors.request.use(config => {
  //config: 请求配置(请求头, 请求参数, 请求类型, 请求路径, ....)
  // console.log('发起请求之前执行');

  // console.log('config ==> ', config);
  let tokenString = localStorage.getItem('token');

  let appkey = 'U2FsdGVkX19WSQ59Cg+Fj9jNZPxRC5y0xB1iV06BeNA=';

  //处理请求的公共参数
  if (config.method === 'get') {
    config.params = config.params || {};
    config.params.appkey = appkey;

    if (tokenUrl.indexOf(config.url) > -1) {
      config.params.tokenString = tokenString;
    }

  } else if (config.method === 'post') {
    config.data = config.data || {};

    if (tokenUrl.indexOf(config.url) > -1) {
      config.data.tokenString = tokenString;
    }

    //序列化post请求参数
    let dataParams = '';
    for (let key in config.data) {
      dataParams += `${key}=${config.data[key]}&`
    }
    dataParams += `appkey=${appkey}`;

    config.data = dataParams;

  }

  //启动加载提示
  Toast.loading({
    message: '加载中...',
    //禁止穿透点击
    forbidClick: true,
    loadingType: 'spinner',
    //不会自动关闭提示
    duration: 0
  })



  return config;
}, err => {
  console.log('err ==> ', err);
  //关闭加载提示
  Toast.clear();
  return Promise.reject(err);
})

//添加一个响应之前拦截器
axios.interceptors.response.use(res => {
  //res: 服务器响应数据
  // console.log('响应数据返回给前端之前');

  //关闭加载提示
  Toast.clear();

  return res;
}, err => {
  console.log('err ==> ', err);

  //关闭加载提示
  Toast.clear();

  return Project.reject(err);
})

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
